package MyDaily.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/*类说明:连接数据库——mydaily
 * 数据库驱动版本:8.0.27
 * */

public class DBconnection {
	// 加载驱动DRIVERNAME
	private static final String DRIVERNAME = "com.mysql.cj.jdbc.Driver";
	// URL路径
	private static String URL = "jdbc:mysql://localhost:3306/mydaily";
	// 数据库账号
	private static final String USER = "root";
	// 数据库密码
	private static final String PASSWORD = "123456";
	// 1.加载驱动
	static {
		try {
			Class.forName(DRIVERNAME);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	// 获取数据库链接
	public static Connection getConnection() throws Exception {
		return DriverManager.getConnection(
				// 指定字符的编码、解码格式
				URL = "jdbc:mysql://127.0.0.1:3306/mydaily?useUnicode=true&characterEncoding=utf8", USER, PASSWORD);
	}

	// 关闭资源
	public static void colse(ResultSet rs, Statement stat, Connection conn) throws Exception {
		try {
			if (rs != null) {
				rs.close();
			}
			if (stat != null) {
				stat.cancel();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		}
	}
	
	public static ResultSet queryData(String sql,Object...datas) throws Exception{
        // 获取连接
        Connection conn = getConnection();
        try {
            // 预处理sql语句
            PreparedStatement ps = conn.prepareStatement(sql);
            // 设置参数
            for(int i=0;i<datas.length;i++){
                ps.setObject(i+1,datas[i]);
            }
            // 执行sql语句
            return ps.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
	
	// 连接检验
	public static void main(String[] args) {
		DBconnection dBcontion = new DBconnection();
		try {
			System.out.println(dBcontion.getConnection());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
